<template>
  <div class="goods-order-list-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">货物订单管理</span>
        </div>
      </template>

      <!-- 搜索和过滤区域 -->
      <div class="search-area">
        <el-form :inline="true">
          <el-form-item label="订单状态">
            <el-select v-model="filterStatus" placeholder="请选择订单状态" clearable style="width: 200px;">
              <el-option
                v-for="option in orderStatusOptions"
                :key="option.value"
                :label="option.label"
                :value="option.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item>
            <el-button @click="resetSearch">重置</el-button>
          </el-form-item>
        </el-form>
      </div>

      <!-- 表格区域 -->
      <div class="table-container">
        <table class="goods-order-table">
          <thead>
            <tr>
              <th>订单编号</th>
              <th>总金额</th>
              <th>运费</th>
              <th>实付金额</th>
              <th>订单状态</th>
              <th>下单时间</th>
              <th>备注</th>
              <th>操作</th>
            </tr>
          </thead>
          <tbody>
            <tr v-for="item in filteredOrders" :key="item.orderId">
              <td>{{ item.orderId }}</td>
              <td>{{ item.totalAmount.toFixed(2) }}</td>
              <td>{{ item.shippingFee.toFixed(2) }}</td>
              <td>{{ item.payableAmount.toFixed(2) }}</td>
              <td>
                <el-tag :type="getOrderStatusType(item.orderStatus)">
                  {{ getOrderStatusText(item.orderStatus) }}
                </el-tag>
              </td>
              <td>{{ formatTimestamp(item.placeOrderTime) }}</td>
              <td>{{ item.remark }}</td>
              <td class="actions-column">
                <div class="action-buttons">
                  <el-button
                    type="primary"
                    link
                    @click="handleViewDetails(item)"
                  >
                    详情
                  </el-button>
                </div>
              </td>
            </tr>
          </tbody>
        </table>
      </div>
    </el-card>

    <!-- 订单详情对话框 -->
    <el-dialog
      v-model="detailsDialogVisible"
      title="订单详情"
      width="50%"
    >
      <div v-if="currentOrderDetails">
        <el-descriptions :column="2" border>
          <el-descriptions-item label="订单编号">{{ currentOrderDetails.cargoOrder.orderId }}</el-descriptions-item>
          <el-descriptions-item label="订单状态">
            <el-tag :type="getOrderStatusType(currentOrderDetails.cargoOrder.orderStatus)">
              {{ getOrderStatusText(currentOrderDetails.cargoOrder.orderStatus) }}
            </el-tag>
          </el-descriptions-item>
          <el-descriptions-item label="商品名称">{{ currentOrderDetails.cargo[0]?.cargoName }}</el-descriptions-item>
          <el-descriptions-item label="商品类型">{{ currentOrderDetails.cargoType[0]?.ctName }}</el-descriptions-item>
          <el-descriptions-item label="数量">{{ currentOrderDetails.cargoOrder.quantity }}</el-descriptions-item>
          <el-descriptions-item label="单价">{{ currentOrderDetails.cargo[0]?.cargoPrice.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="总金额">{{ currentOrderDetails.cargoOrder.totalAmount.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="运费">{{ currentOrderDetails.cargoOrder.shippingFee.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="应付金额">{{ currentOrderDetails.cargoOrder.payableAmount.toFixed(2) }}</el-descriptions-item>
          <el-descriptions-item label="下单时间">{{ formatTimestamp(currentOrderDetails.cargoOrder.placeOrderTime) }}</el-descriptions-item>
          <el-descriptions-item label="生产日期">{{ formatTimestamp(currentOrderDetails.cargo[0]?.produceDate) }}</el-descriptions-item>
          <el-descriptions-item label="保质期">{{ currentOrderDetails.cargo[0]?.sellBy }}</el-descriptions-item>
          <el-descriptions-item label="商品描述" :span="2">{{ currentOrderDetails.cargo[0]?.cargoDescribe }}</el-descriptions-item>
          <el-descriptions-item label="备注" :span="2">{{ currentOrderDetails.cargoOrder.remark || '无' }}</el-descriptions-item>
        </el-descriptions>
      </div>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { ElMessage } from 'element-plus'
import { cargoOrderApi } from '../api/console'

// 接口类型定义
interface CargoType {
  ctId: number
  ctName: string
}

interface Cargo {
  cargoId: number
  cargoName: string
  ctId: number
  cargoPrice: number
  produceDate: number
  sellBy: string
  cargoDescribe: string
}

interface CargoOrder {
  orderId: number
  cargoId: number
  orderStatus: number
  quantity: number
  totalAmount: number
  shippingFee: number
  payableAmount: number
  placeOrderTime: number
  remark: string
}

interface CargoOrderDetail {
  cargoOrder: CargoOrder
  cargoType: CargoType[]
  cargo: Cargo[]
}

// 状态定义
const loading = ref(false)
const orders = ref<CargoOrder[]>([])
const filterStatus = ref<number | ''>('')

const detailsDialogVisible = ref(false)
const currentOrderDetails = ref<CargoOrderDetail | null>(null)

// 订单状态选项
const orderStatusOptions = [
  { value: 0, label: '配送中' },
  { value: 1, label: '已送达' }
]

// 计算属性：过滤后的订单列表
const filteredOrders = computed(() => {
  return orders.value.filter(order => {
    const statusMatch = filterStatus.value === '' || order.orderStatus === filterStatus.value
    return statusMatch
  })
})

// 获取订单列表
const fetchOrders = async () => {
  try {
    loading.value = true
    const result = await cargoOrderApi.getAllCargoOrders()
    if (result.code === 200 && result.data) {
      orders.value = result.data
    } else {
      ElMessage.error(result.message || '获取订单列表失败')
    }
  } catch (error) {
    ElMessage.error('获取订单列表失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 获取订单状态类型
const getOrderStatusType = (status: number) => {
  switch (status) {
    case 0:
      return 'warning'
    case 1:
      return 'success'
    default:
      return 'info'
  }
}

// 获取订单状态文本
const getOrderStatusText = (status: number) => {
  switch (status) {
    case 0:
      return '配送中'
    case 1:
      return '已送达'
    default:
      return '未知状态'
  }
}

// 格式化时间戳
const formatTimestamp = (timestamp: number | string | null): string => {
  if (!timestamp) return '-'
  const time = typeof timestamp === 'string' ? parseInt(timestamp, 10) : timestamp
  if (isNaN(time)) return '-'

  const date = new Date(time)
  const year = date.getFullYear()
  const month = String(date.getMonth() + 1).padStart(2, '0')
  const day = String(date.getDate()).padStart(2, '0')
  const hours = String(date.getHours()).padStart(2, '0')
  const minutes = String(date.getMinutes()).padStart(2, '0')
  const seconds = String(date.getSeconds()).padStart(2, '0')

  return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`
}

// 重置搜索
const resetSearch = () => {
  filterStatus.value = ''
}

// 处理查看详情
const handleViewDetails = async (order: CargoOrder) => {
  try {
    loading.value = true
    const result = await cargoOrderApi.getCargoOrderDetails(order.orderId)
    if (result.code === 200 && result.data) {
      currentOrderDetails.value = result.data
      detailsDialogVisible.value = true
    } else {
      ElMessage.error(result.message || '获取订单详情失败')
    }
  } catch (error) {
    ElMessage.error('获取订单详情失败')
    console.error(error)
  } finally {
    loading.value = false
  }
}

// 页面加载时获取数据
onMounted(async () => {
  await fetchOrders()
})
</script>

<style scoped>
.goods-order-list-container {
  margin-left: 200px;
  margin-top: 45px;
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.search-area {
  margin-bottom: 20px;
}

.table-container {
  width: 100%;
  overflow-x: auto;
}

.goods-order-table {
  width: 100%;
  border-collapse: collapse;
  margin-top: 20px;
  min-width: 1000px;
}

.goods-order-table th,
.goods-order-table td {
  border: 1px solid #ddd;
  padding: 12px;
  text-align: center;
  color: #333;
  vertical-align: middle;
}

.goods-order-table th {
  background-color: #f2f2f2;
  font-weight: bold;
  color: #333;
}

.goods-order-table tbody tr:nth-child(even) {
  background-color: #f9f9f9;
}

.goods-order-table tbody tr:hover {
  background-color: #f5f5f5;
}

.actions-column {
  white-space: nowrap;
  display: flex;
  justify-content: center;
  align-items: center;
  min-width: 120px;
  height: 60px;
}

.action-buttons {
  display: flex;
  gap: 8px;
  justify-content: center;
  width: 100%;
}

.action-buttons .el-button {
  display: flex;
  align-items: center;
  gap: 4px;
  margin: 0;
}

:deep(.el-select) {
  width: 100%;
}

/* 响应式布局 */
@media screen and (max-width: 768px) {
  .goods-order-list-container {
    margin-left: 0;
    width: 100%;
    padding: 10px;
  }

  .card-header {
    flex-direction: column;
    gap: 16px;
  }

  .title {
    width: 100%;
    text-align: center;
  }

  .search-area {
    .el-form {
      display: flex;
      flex-direction: column;
      gap: 10px;
    }

    .el-form-item {
      margin: 0 !important;
      width: 100%;
    }
  }

  .el-button {
    width: 100%;
    justify-content: center;
  }
}
</style> 